import React, { useState, useEffect } from 'react';
import { menuApi } from '../services/api';

const MenuManagement = () => {
  const [menus, setMenus] = useState([]);
  const [loading, setLoading] = useState(false);
  const [editingMenu, setEditingMenu] = useState(null);
  const [showForm, setShowForm] = useState(false);
  const [formData, setFormData] = useState({
    name: '',
    path: '',
    icon: '',
    parentId: '',
    order: 0,
    permissions: ['admin', 'developer', 'user']
  });
  const [menuTree, setMenuTree] = useState([]);
  const [viewMode, setViewMode] = useState('table'); // 'table' or 'tree'

  useEffect(() => {
    loadMenus();
    loadMenuTree();
  }, []);

  const loadMenus = async () => {
    try {
      setLoading(true);
      const data = await menuApi.getMenus();
      setMenus(data);
    } catch (error) {
      console.error('加载菜单失败:', error);
      alert('加载菜单失败，请检查后端服务是否启动');
    } finally {
      setLoading(false);
    }
  };

  const loadMenuTree = async () => {
    try {
      const tree = await menuApi.getMenuTree();
      setMenuTree(tree);
    } catch (error) {
      console.error('加载菜单树失败:', error);
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      if (editingMenu) {
        await menuApi.updateMenu(editingMenu.id, formData);
      } else {
        await menuApi.createMenu({
          ...formData,
          parentId: formData.parentId ? parseInt(formData.parentId) : null
        });
      }
      
      setShowForm(false);
      setEditingMenu(null);
      setFormData({
        name: '',
        path: '',
        icon: '',
        parentId: '',
        order: 0,
        permissions: ['admin', 'developer', 'user']
      });
      await loadMenus();
    } catch (error) {
      console.error('保存菜单失败:', error);
      alert('保存菜单失败');
    }
  };

  const handleEdit = (menu) => {
    setEditingMenu(menu);
    setFormData({
      name: menu.name,
      path: menu.path,
      icon: menu.icon,
      parentId: menu.parentId || '',
      order: menu.order,
      permissions: menu.permissions || ['admin', 'developer', 'user']
    });
    setShowForm(true);
  };

  const handleDelete = async (id) => {
    if (confirm('确定要删除这个菜单吗？')) {
      try {
        await menuApi.deleteMenu(id);
        await loadMenus();
        await loadMenuTree();
      } catch (error) {
        console.error('删除菜单失败:', error);
        alert('删除菜单失败');
      }
    }
  };

  const resetForm = () => {
    setEditingMenu(null);
    setFormData({
      name: '',
      path: '',
      icon: '',
      parentId: '',
      order: 0,
      permissions: ['admin', 'developer', 'user']
    });
    setShowForm(false);
  };

  return (
    <div className="space-y-6">
      {/* Header */}
      <div className="bg-white/10 backdrop-blur-lg rounded-2xl p-6 border border-white/20">
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-3xl font-bold text-white mb-2">菜单管理</h1>
            <p className="text-blue-200">管理系统菜单和权限配置</p>
          </div>
          <div className="flex gap-4">
            <div className="flex bg-white/10 rounded-lg p-1">
              <button
                onClick={() => setViewMode('table')}
                className={`px-3 py-1 rounded-md transition-colors ${
                  viewMode === 'table' ? 'bg-white/20 text-white' : 'text-blue-300'
                }`}
              >
                表格视图
              </button>
              <button
                onClick={() => setViewMode('tree')}
                className={`px-3 py-1 rounded-md transition-colors ${
                  viewMode === 'tree' ? 'bg-white/20 text-white' : 'text-blue-300'
                }`}
              >
                树形视图
              </button>
            </div>
            <button
              onClick={() => setShowForm(true)}
              className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg transition-colors"
            >
              添加菜单
            </button>
          </div>
        </div>
      </div>

      {showForm && (
        <div className="bg-white/10 backdrop-blur-lg rounded-2xl p-6 border border-white/20">
          <h2 className="text-xl font-semibold text-white mb-4">
            {editingMenu ? '编辑菜单' : '添加菜单'}
          </h2>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">
                  菜单名称
                </label>
                <input
                  type="text"
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  required
                />
              </div>
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">
                  路径
                </label>
                <input
                  type="text"
                  value={formData.path}
                  onChange={(e) => setFormData({ ...formData, path: e.target.value })}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  required
                />
              </div>
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">
                  图标
                </label>
                <input
                  type="text"
                  value={formData.icon}
                  onChange={(e) => setFormData({ ...formData, icon: e.target.value })}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  placeholder="例如: home, users, server"
                  required
                />
              </div>
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">
                  父菜单
                </label>
                <select
                  value={formData.parentId}
                  onChange={(e) => setFormData({ ...formData, parentId: e.target.value })}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white focus:outline-none focus:border-blue-500"
                >
                  <option value="" className="bg-gray-800 text-white">顶级菜单</option>
                  {menus.filter(menu => !menu.parentId).map(menu => (
                    <option key={menu.id} value={menu.id} className="bg-gray-800 text-white">{menu.name}</option>
                  ))}
                </select>
              </div>
              <div>
                <label className="block text-blue-200 text-sm font-medium mb-2">
                  排序
                </label>
                <input
                  type="number"
                  value={formData.order}
                  onChange={(e) => setFormData({ ...formData, order: parseInt(e.target.value) || 0 })}
                  className="w-full px-3 py-2 bg-gray-800 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:border-blue-500"
                  required
                />
              </div>
              <div className="md:col-span-2">
                <label className="block text-blue-200 text-sm font-medium mb-2">
                  权限
                </label>
                <div className="flex flex-wrap gap-4">
                  {['admin', 'developer', 'user'].map(permission => (
                    <label key={permission} className="flex items-center">
                      <input
                        type="checkbox"
                        checked={formData.permissions.includes(permission)}
                        onChange={(e) => {
                          const newPermissions = e.target.checked
                            ? [...formData.permissions, permission]
                            : formData.permissions.filter(p => p !== permission);
                          setFormData({ ...formData, permissions: newPermissions });
                        }}
                        className="mr-2 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                      <span className="text-white text-sm">{permission}</span>
                    </label>
                  ))}
                </div>
              </div>
            </div>
            <div className="flex gap-2">
              <button
                type="submit"
                className="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg transition-colors"
              >
                {editingMenu ? '更新' : '创建'}
              </button>
              <button
                type="button"
                onClick={resetForm}
                className="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg transition-colors"
              >
                取消
              </button>
            </div>
          </form>
        </div>
      )}

      <div className="bg-white/10 backdrop-blur-lg rounded-2xl border border-white/20 overflow-hidden">
        {loading ? (
          <div className="p-8 text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500 mx-auto"></div>
            <p className="mt-2 text-gray-600">加载中...</p>
          </div>
        ) : viewMode === 'table' ? (
          <table className="min-w-full divide-y divide-gray-200">
            <thead>
              <tr>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-300 uppercase tracking-wider">
                  菜单名称
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-300 uppercase tracking-wider">
                  路径
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-300 uppercase tracking-wider">
                  图标
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-300 uppercase tracking-wider">
                  父菜单
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-300 uppercase tracking-wider">
                  排序
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-300 uppercase tracking-wider">
                  权限
                </th>
                <th className="px-6 py-3 text-left text-xs font-medium text-blue-300 uppercase tracking-wider">
                  操作
                </th>
              </tr>
            </thead>
            <tbody className="divide-y divide-white/5">
              {menus.map((menu) => (
                <tr key={menu.id} className="hover:bg-white/5 transition-colors duration-200">
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm font-medium text-white">{menu.name}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-blue-300">{menu.path}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-blue-300">{menu.icon}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-blue-300">
                      {menu.parentId ? menus.find(m => m.id === menu.parentId)?.name || '未知' : '顶级菜单'}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="text-sm text-blue-300">{menu.order}</div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap">
                    <div className="flex flex-wrap gap-1">
                      {menu.permissions?.map(permission => (
                        <span key={permission} className="px-2 py-1 text-xs bg-blue-500/20 text-blue-300 rounded-full">
                          {permission}
                        </span>
                      ))}
                    </div>
                  </td>
                  <td className="px-6 py-4 whitespace-nowrap text-sm font-medium">
                    <button
                      onClick={() => handleEdit(menu)}
                      className="text-blue-400 hover:text-blue-300 mr-3 transition-colors duration-200"
                    >
                      编辑
                    </button>
                    <button
                      onClick={() => handleDelete(menu.id)}
                      className="text-red-400 hover:text-red-300 transition-colors duration-200"
                    >
                      删除
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        ) : (
          <div className="p-6">
            <h3 className="text-lg font-semibold mb-4">菜单树形结构</h3>
            <div className="space-y-2">
              {menuTree.map(menu => (
                <MenuTreeNode 
                  key={menu.id} 
                  menu={menu} 
                  level={0}
                  onEdit={handleEdit}
                  onDelete={handleDelete}
                />
              ))}
            </div>
          </div>
        )}
      </div>
    </div>
  );
};

// 菜单树节点组件
const MenuTreeNode = ({ menu, level, onEdit, onDelete }) => {
  const [expanded, setExpanded] = useState(true);

  return (
    <div className="ml-4">
      <div className="flex items-center justify-between p-3 bg-white/5 rounded-lg hover:bg-white/10 transition-colors duration-200">
        <div className="flex items-center gap-3">
          <div style={{ marginLeft: `${level * 20}px` }}></div>
          {menu.children && menu.children.length > 0 && (
            <button
              onClick={() => setExpanded(!expanded)}
              className="text-gray-500 hover:text-gray-700"
            >
              {expanded ? '▼' : '▶'}
            </button>
          )}
          <div className="flex items-center gap-2">
            <span className="text-lg">{menu.icon}</span>
            <div>
              <div className="font-medium">{menu.name}</div>
              <div className="text-sm text-gray-500">{menu.path}</div>
            </div>
          </div>
        </div>
        <div className="flex gap-2">
          <button
            onClick={() => onEdit(menu)}
            className="text-blue-600 hover:text-blue-900 text-sm"
          >
            编辑
          </button>
          <button
            onClick={() => onDelete(menu.id)}
            className="text-red-600 hover:text-red-900 text-sm"
          >
            删除
          </button>
        </div>
      </div>
      {expanded && menu.children && menu.children.map(child => (
        <MenuTreeNode 
          key={child.id} 
          menu={child} 
          level={level + 1}
          onEdit={onEdit}
          onDelete={onDelete}
        />
      ))}
    </div>
  );
};

export default MenuManagement;